import React, { useState } from 'react';
import { Checkbox } from 'antd';
import { uniqBy, filter, map, difference, union, groupBy, cloneDeep } from 'lodash-es';
import { Input, Loading } from '@knownsec/react-component';
import s from './style.module.less';
import cn from 'classnames';
import { pluginList } from '~/API';

export default function treeModel({ list, onChange, init=[] }) {
    const [templateVuls, setTemplateVuls] = useState(groupBy(list, 'category_cn'));
    const [templateCheckValue, setTemplateCheckValue] = useState(init);
    const [vulTemplateKeys, setVulTemplateKeys] = useState({});
    const [templateDisabled, setTemplateDisabled] = useState(false);
    const [searchVal, setSearchVal] = useState();
    const [loading, setLoading] = useState(false);

    const onClickShowVulsItem = (key) => {
        let vulTemplateKeys_ = cloneDeep(vulTemplateKeys);
        vulTemplateKeys_[key] = !vulTemplateKeys_[key];
        setVulTemplateKeys(vulTemplateKeys_);
    };
    const onTemplateChange = (value, group) => {
        let templateCheckValue_ = cloneDeep(templateCheckValue);
        let newGroup = group.map(({ key_name }) => key_name);
        let unchecked = difference(newGroup, value);
        templateCheckValue_ = union(templateCheckValue_, value);
        templateCheckValue_ = difference(templateCheckValue_, unchecked);
        setTemplateCheckValue(templateCheckValue_);
        onChange(templateCheckValue_);
    };
    const onGroupCheckAll = (e, value) => {
        let templateCheckValue_ = templateCheckValue;
        if (e.target.checked) {
            templateCheckValue_ = union(templateCheckValue_, value);
        } else {
            templateCheckValue_ = difference(templateCheckValue_, value);
        }
        onChange(templateCheckValue_);
        setTemplateCheckValue(templateCheckValue_);
    };
    const onSearch = async (e) => {
        setLoading(true);
        const list = await pluginList({ search_key: e.value });
        const data = list?.data?.plugin_list || [];
        let pl = uniqBy(data, 'key');
        pl = pl.map((item) => {
            const i = {
                cn_name: item.name.zh_cn || '-',
                en_name: item.name.en_us || '-',
                key_name: item.key,
                category_cn: item.vuln_type[0].zh_cn,
                category_en: item.vuln_type[0].en_us,
            };
            return i;
        });
        setTemplateVuls(groupBy(pl, 'category_cn'));
        setLoading(false);
    };
    React.useEffect(() => {
        onChange(templateCheckValue);
        if (init) {
            setTemplateCheckValue(init);
        }
    }, [init]);
    return (
        <div className={s.treeBox}>
            <div className={s.vulBox}>
                <Input
                    pro
                    value={searchVal}
                    search
                    clear
                    onSearch={onSearch}
                    className={s.searchInp}
                    placeholder="请输入漏洞名称"
                    maxlength={16}
                    autoComplete={'off'}
                    onChange={(e) => {
                        setSearchVal(e.value);
                        // if (!e.value) {
                        //     onSearch(e)
                        //   }
                    }}
                />
                <div className={s.vulBoxSel}>
                    <Loading show={loading} />
                   {!Object.keys(templateVuls)[0]&& <div className={s.noSearch}>未搜索到对应内容</div>} 
                    {map(templateVuls, (group, key) => {
                        let groupValue = [];
                        let checked = [];
                        if (templateCheckValue) {
                            checked = filter(group, (item) => {
                                return templateCheckValue.includes(item.key_name);
                            });
                            group.forEach((item) => {
                                groupValue.push(item.key_name);
                            });
                        }
                        return (
                            <div key={key} style={{ margin: '8px 0' }}>
                                <div style={{ cursor: 'pointer' }}>
                                    {vulTemplateKeys[key] ? (
                                        <div
                                            className={s.icon}
                                            onClick={() => {
                                                onClickShowVulsItem(key);
                                            }}
                                        >
                                            -
                                        </div>
                                    ) : (
                                        <div
                                            className={s.icon}
                                            onClick={() => {
                                                onClickShowVulsItem(key);
                                            }}
                                        >
                                            +
                                        </div>
                                    )}
                                    &nbsp;
                                    <Checkbox
                                        indeterminate={
                                            checked.length && checked.length < groupValue.length
                                        }
                                        checked={checked.length === groupValue.length}
                                        disabled={templateDisabled}
                                        onChange={(e) => onGroupCheckAll(e, groupValue)}
                                    />
                                    &nbsp;
                                    <span
                                        onClick={() => {
                                            onClickShowVulsItem(key);
                                        }}
                                    >
                                        {key}
                                    </span>
                                    ({`${checked.length || 0}/${group.length}`})
                                </div>
                                <div
                                    className={s.vulsItemBox}
                                    style={{
                                        display: vulTemplateKeys[key] ? 'block' : 'none',
                                    }}
                                >
                                    <Checkbox.Group
                                        value={templateCheckValue}
                                        onChange={(value) => onTemplateChange(value, group)}
                                        style={{ display: 'flex', flexDirection: 'column' }}
                                    >
                                        {group.map((item, i) => {
                                            return (
                                                <Checkbox
                                                    value={item.key_name}
                                                    style={{ margin: '4px 0' }}
                                                    disabled={templateDisabled}
                                                    key={i}
                                                >
                                                    {item.cn_name}
                                                </Checkbox>
                                            );
                                        })}
                                    </Checkbox.Group>
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>
        </div>
    );
}
